Views should not be responsible for directly triggering coroutines. Hence, ViewModel
classes should prefer creating coroutines instead
of exposing suspending functions to perform some piece of business logic. This allows for easier testing of your application, as
ViewModel
classes can be unit tested, whereas views require instrumentation tests.
Please refer to the Android docs for
more advanced examples and mechanisms of updating the views with data generated asynchronously.
This rule raises an issue when suspending functions are exposed by classes inheriting from ViewModel
.
Noncompliant code example
class MyViewModel : ViewModel() {
suspend fun performAction() = suspendingWorker()
}
Compliant solution
class MyViewModel : ViewModel() {
fun performAction() =
viewModelScope.launch {
suspendingWorker()
}
}